package audio;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import ddf.minim.AudioSnippet;

public class BombSample extends TimerTask{
	
	public static final long DURATION_TICK	= 4500l;
	public static final long DELAY_START	= 500l;
	public static final long DELAY_END		= 40l;
	
	AudioSnippet	_tick;
	AudioSnippet	_boom;
	Timer			_timer;
	TimerTask		_task;
	
	private long	_timeInit	= -1;
	private long	_timePlay	= -1;
	private long	_timePlayed	= -1;
	private long	_interval	= 40;
	
	private boolean	_flgBoom	= false;
	
	
	public BombSample () {
		//_tick		= Audio.getSnippet ("tick.wav");
		_tick		= Audio.getSnippet ("tick_test.wav");
		_boom		= Audio.getSnippet ("bang0" + (int) (1 + Math.random ()) + ".wav");
//		_boom		= Audio.getSnippet ("bang01_test.wav");
		_timeInit	= new Date ().getTime ();
		
		play ();
		
		_timer		= new Timer ();
		_timer.schedule (this, 0l, _interval);
	}
	
	public void run () {
		float	prog	= timePlaying () / (float) DURATION_TICK;
		long	gap		= (long) (DELAY_START + (DELAY_END - DELAY_START) * prog);
		
		if (!_flgBoom){
			if (gap < new Date ().getTime () - _timePlayed){
				play ();
			}
		}
	}
	
	private void play () {
		if (_timePlay == -1) {
			_timePlay = new Date ().getTime ();
		}
		_timePlayed = new Date ().getTime ();
		_tick.rewind ();
		_tick.play ();
	}
	
	public void explode () {
		_flgBoom = true;
		_timer.cancel ();
		_boom.play ();
	}
	
	public void stop () {
		_flgBoom = true;
		_timer.cancel ();
	}
	
	public long timeInit () {
		return new Date ().getTime () - _timeInit;
	}
	
	public long timePlaying () {
		return new Date ().getTime () - _timePlay;
	}
	
	public long timeLastPlayed () {
		return new Date ().getTime () - _timePlayed;
	}
}